package com.hx.zhg.web.help;

import com.hx.zhg.web.factory.ThreadLocalFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 一些servlet context 相关系统公共处理
 */
public class ServletContextEnvHelp {

    private static final Logger log = LoggerFactory.getLogger(ServletContextEnvHelp.class);

    /**
     * 得到request实例
     *
     * @return
     */
    public static HttpServletRequest getRequestInstance() {
        return ThreadLocalFactory.getRequestThreadlocal().get();
    }

    /**
     * 得到response实例
     *
     * @return
     */
    public static HttpServletResponse getResponseInstance() {
        return ThreadLocalFactory.getResponseThreadlocal().get();
    }

    /**
     * 得到session实例
     *
     * @return
     */
    public static HttpSession getSessionInstance() {
        HttpServletRequest request = getRequestInstance();
        if (request == null) {
            return null;
        }
        return request.getSession();
    }

    /**
     * 得到ApplicationContext实例
     *
     * @return
     */
    public static ApplicationContext getApplicationContextInstance() {
        HttpServletRequest request = getRequestInstance();
        if (request == null) {
            return null;
        }
        ApplicationContext applicationContext =
                WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return applicationContext;
    }

    /**
     * 得到response的writer实例
     *
     * @return
     */
    public static PrintWriter getResponseWriterInstance(String contentType) {
        HttpServletResponse response = getResponseInstance();
        if (response == null) {
            return null;
        }
        response.setContentType(contentType);
        try {
            return response.getWriter();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 得到response的writer实例
     *
     * @return
     */
    public static PrintWriter getResponseWriterInstance() {
        HttpServletResponse response = getResponseInstance();
        if (response == null) {
            return null;
        }
        try {
            return response.getWriter();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

}
